﻿package com.adsame.utils
{
	import flash.utils.*;

	import com.adsame.interfaces.*;

	/**
	 * AsamIterator 
	 * 
	 * @uses IAsamIterator
	 * @package 
	 * @version $id$
	 * @copyright Powered By Adsame 2008-2009 (c)
	 * @author olga 
	 * @license 
	 */
	public class AsamIterator implements IAsamIterator
	{
		protected var __p_current 	: Object = null;

		protected var __p_first		: Object = null;

		protected var __data 		: Dictionary = new Dictionary(true);


		public function add(data : Object, index : String) :void
		{
			var data_info : Object = {
				p_next 		: null,
		 		p_prev 		: null,
				name_p_next : null,
				name_p_prev : null,
				p_data 		: data
			};

			if (this.__p_current)
			{
				data_info.p_prev = this.__p_current;
				data_info.p_next = this.__p_current.p_next;
				this.__p_current.p_next = data_info;
				this.__p_current = data_info;
			} else {
				this.__p_first = data_info;
				this.__p_current = data_info;
			}

			if (!this.__data[index])
			{
				this.__data[index] = data_info;
			}
			else
			{
				data_info.name_p_next = this.__data[index];
				this.__data[index].name_p_prev = data_info;
				this.__data[index] = data_info;
			}
		}

		public function getByName(index : String) : Object
		{
			if (!this.__data[index])
				return null;

			return this.__data[index].p_data;
		}

		public function get() : Object
		{
			if (!this.__p_current)
				return null;

			return this.__p_current.p_data;
		}

		public function next() : Object
		{
			if (!this.__p_current || !this.__p_current.p_next)
				return null;

			this.__p_current = this.__p_current.p_next;
			var reval : Object = this.__p_current.p_data;
			return reval;
		}

		public function prev() : Object
		{
			if (!this.__p_current || !this.__p_current.p_prev)
				return null;

			this.__p_current = this.__p_current.p_prev;
			var reval : Object = this.__p_current.p_data;
			return reval;
		}

		public function each(callback : Function, scope : Object) : Boolean
		{
			var p_current : Object = this.__p_first;

			if (!p_current)
			{
				return false;
			}
			else
			{
				callback.call(scope, p_current.p_data);
				while (p_current.p_next)
				{
					p_current = p_current.p_next;
					callback.call(scope, p_current.p_data);
				}
				return true;
			}
		}

		public function eachByName(index : String, callback : Function, scope : Object) : Boolean
		{
			if (!this.__data[index])
				return false;

			var p_current : Object = this.__data[index];
			callback.call(scope, p_current.p_data);
			while (p_current.name_p_next)
			{
				p_current = p_current.name_p_next;
				callback.call(scope, p_current.p_data);
			}

			return true;
		}
	}
}
